package com.cyq.config;

import com.cyq.mapper.UserMapper;
import com.cyq.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    /*授权
    *   获取角色权限信息*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权方法->doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        /*为当前对象赋予perms权限*/
//        info.addStringPermission("emp:emp");
        //1. 拿到当前登录的对象
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
        //3. 设置当前用户权限
        List<String> adminPermissions= Arrays.asList("admin:bill","admin:provider","admin:role","admin:user","admin:pwd");
        List<String> masterPermissions= Arrays.asList("master:bill","master:provider","master:user","master:pwd");
        List<String> employeePermissions= Arrays.asList("employee:pwd");

        switch (currentUser.getUserRole()){
            case 1:
                info.addRole("admin");
                info.addStringPermission(String.valueOf(adminPermissions));
                break;
            case 2:
                info.addRole("master");
                info.addStringPermission(String.valueOf(masterPermissions));
                break;
            case 3:
                info.addRole("employee");
                info.addStringPermission(String.valueOf(employeePermissions));
                break;
        }
        System.out.println(info.getRoles());
        return info;
    }

    /*认证
    *   获取用户凭证信息*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证方法->doGetAuthenticationInfo");
        //获取token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //连接真实的数据库
        User user = new User();
        user.setUserCode(token.getUsername());      //从token中获取用户名

        user = userMapper.queryUserByUser(user);
        //没有这个用户
        if (user == null) {
            return null;    //相当于UnknownAccountException异常
        }
        //密码认证，这里已经不显示密码验证而是由shiro自己来做
        return new SimpleAuthenticationInfo(user, user.getUserPassword(), "");
    }
}
